#!/home/python/.virtualenvs/open/bin/python

import sys
sys.path.append('./')
sys.path.insert(0, "../")

import os
if not os.getenv('DJANGO_SETTINGS_MODULE'):
    os.environ['DJANGO_SETTINGS_MODULE'] = 'equity_mall.settings.dev'

import django
django.setup()

from Crypto.Cipher import AES
import base64, datetime, json, requests, time, xlrd, pymysql, uuid, paramiko, hashlib
from django.conf import settings
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA256, SHA1, SHA, SHA512, MD5
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
import Crypto.Signature.PKCS1_v1_5 as sign_PKCS1_v1_5
from random import Random
from django.db.models import Count, Sum, Max, Min, Avg
from decimal import Decimal
from fpdf import FPDF
from random import randint
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives.ciphers import algorithms

from merchants.models import MerchantBill, MerchantSettlementRecord, MerchantChannel, MerchantBillSettlementRecord, Merchant, MerchantNFCDevice, MerchantNFCDeviceTrade, MerchantEightEightActivity, MerchantEightEightWhiteTable
from speeds.models import SpeedMerchantAuthDraw
from equity_mall.utils.qiniu_storage import pic_upload
from activities.models import Channel
from merchants.slideVerfication import SlideVerificationCode
from equity_mall.utils.add_merchant import add_merchant_info
from equity_mall.utils.utils import get_sign

BLOCK_SIZE = AES.block_size
pad = lambda s: s + (BLOCK_SIZE - len(s.encode()) % BLOCK_SIZE) * chr(BLOCK_SIZE - len(s.encode()) % BLOCK_SIZE)
unpad = lambda s: s[:-ord(s[len(s) - 1:])]


def add_to_16(text):
    if len(text.encode('utf-8')) % 16:
        add = 16 - (len(text.encode('utf-8')) % 16)
    else:
        add = 0
    text = text + ('\0' * add)
    return text.encode('utf-8')

def pkcs7_padding(data):
    if not isinstance(data, bytes):
        data = data.encode()
    padder = padding.PKCS7(algorithms.AES.block_size).padder()
    padded_data = padder.update(data) + padder.finalize()
    return padded_data


def encrypt_ECB(text, key):
    key = key.encode('utf-8')
    mode = AES.MODE_ECB
    cryptos = AES.new(key, mode)
    text = pkcs7_padding(text.encode('utf-8'))
    cipher_text = cryptos.encrypt(text)
    return base64.b64encode(cipher_text).decode('utf-8')


def random_str(randomlength=32):
    strs = ''
    chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    length = len(chars) - 1
    random = Random()
    for i in range(randomlength):
        strs += chars[random.randint(0, length)]
    return strs


class AESCipher:

    def __init__(self, secretkey, iv):
        self.key = secretkey
        self.iv = iv

    def encrypt(self, text):

        text = pad(text).encode()
        cipher = AES.new(key=base64.b64decode(self.key.encode()), mode=AES.MODE_CBC, IV=self.iv.encode())
        encrypted_text = cipher.encrypt(text)
        return base64.b64encode(encrypted_text).decode('utf-8')

    def decrypt(self, encrypted_text):

        encrypted_text = base64.b64decode(encrypted_text)
        cipher = AES.new(key=base64.b64decode(self.key.encode()), mode=AES.MODE_CBC, IV=self.iv.encode())
        decrypted_text = cipher.decrypt(encrypted_text)
        return unpad(decrypted_text).decode('utf-8')


def get_message(data_dict, message):

    params_list = sorted(data_dict.items(), key=lambda e: e[0], reverse=False)
    params_str = "&".join(u"{}={}".format(k, v) for k, v in params_list)
    return message + "&" + params_str


class RSACipher:

    def __init__(self, pubkey, privkey):
        self.pubkey = self._format_public_key(pubkey)  # 密钥
        self.privkey = self._format_private_key(privkey)  # 偏移量

    def _format_private_key(self, private_key):
        __pem_begin = '-----BEGIN RSA PRIVATE KEY-----\n'
        __pem_end = '\n-----END RSA PRIVATE KEY-----'
        if not private_key.startswith(__pem_begin):
            private_key = __pem_begin + private_key
        if not private_key.endswith(__pem_end):
            private_key = private_key + __pem_end
        return private_key

    def _format_public_key(self, public_key):
        __pem_begin = '-----BEGIN RSA PUBLIC KEY-----\n'
        __pem_end = '\n-----END RSA PUBLIC KEY-----'
        if not public_key.startswith(__pem_begin):
            public_key = __pem_begin + public_key
        if not public_key.endswith(__pem_end):
            public_key = public_key + __pem_end
        return public_key

    def rsaEncrypt(self, message):
        msg = message.encode('utf-8')
        rsakey = RSA.importKey(self.pubkey)
        cipher = Cipher_pkcs1_v1_5.new(rsakey)
        cipher_text = base64.b64encode(cipher.encrypt(msg))
        return cipher_text

    def rsaDecrypt(self, result):
        msg = result.encode('utf-8')
        rsakey = RSA.importKey(self.privkey)
        cipher = Cipher_pkcs1_v1_5.new(rsakey)
        text = cipher.decrypt(base64.b64decode(msg), b'ERROR')
        return text.decode('utf-8')

    def sign(self, message):
        rsakey = RSA.importKey(self.privkey)
        cipher = sign_PKCS1_v1_5.new(rsakey)
        rand_hash = SHA256.new()
        rand_hash.update(message.encode())
        signature = cipher.sign(rand_hash)
        return str((base64.b64encode(signature)), encoding="utf-8")

    def verify(self, message, signature):
        key = RSA.importKey(self.pubkey)
        rand_hash = SHA256.new()
        rand_hash.update(message.encode())
        verifier = sign_PKCS1_v1_5.new(key)
        if not verifier.verify(rand_hash, base64.b64decode(signature)):
            return False
        else:
            return True


def query_transettletoday(s_merInId):
    publicKey = '''MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0CzGDOwz5IcPA+/EhLt98G7EKUhE90U1v162xqXDzL8t+2Ok+iBnZQFFqWNB6gnID7GzaUVrDaNQX1vFLcCvhCgMgvOa973xFjeDJPXF/xUQboagWkZb8EGxiyympbN8SO4mey9Ldn9EX3m+yKuqvCrJTEKK0Gqg/Y/Dr3oCzC8KdesAb6x/ZTccsyHVPrzZ5LUkIMFVb4QVAFcI6/aa3G4GpZwLdsxrUnJ1k8kjYgx0GfC6Z0M665Z+lZpt+bQjk/ZwEHkbAjleREz/DPiefBbfGP/UKgLjcRxTN8mPHzT1SHw1U8hV4zFyJkGAOL+b8Bg4LAuHwveoeMYmf3kGeQIDAQAB'''
    privateKey = '''MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDQLMYM7DPkhw8D78SEu33wbsQpSET3RTW/XrbGpcPMvy37Y6T6IGdlAUWpY0HqCcgPsbNpRWsNo1BfW8UtwK+EKAyC85r3v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wozpUrU6pQ8pPWvckUrnpmhKXiPYKZLubv7hb5e6Dp0ZHPwWSRpPIEt6e3TyOrZwgW1nP/ouhWfy8IY4r1xitfh5rm7ScSF/5IkLTphB4zN1YTgOomyLjNwrUSquSqXUNsCgYEAx0Nbfq+AzCS3fgm3d0Rh2LMjzmr+SdJa6LVOPiRORl9g4kvUVo5oRmFTxMMgJFEu+2e1yKCzx9P8byN2X90ggHw64bnnfNtybFo7LWfK//CDWeF2pKCYFHLI2etr1in7NKpWe6TpGtfzQwc1cQG7dj3UEHhmL37qXu4hCsx0KDs='''
    url = 'https://rjp.ruiyinxin.com/nms/ims/tranSt/tranStTodayList'
    reqTime = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
    aesKey = random_str(43) + '='
    ivParam = random_str(16)
    encryptKey_json = json.dumps({"aesKey": aesKey, "ivParam": ivParam})
    aes_cipher = AESCipher(aesKey, ivParam)
    rsa_cipher = RSACipher(publicKey, aceessPrivateKey)
    info = aes_cipher.encrypt(json.dumps({"s_merInId": s_merInId}))
    message = f'accessId=000000000000000&reqTime={reqTime}&ivParam={ivParam}&s_merInId={s_merInId}'
    sign = rsa_cipher.sign(message)
    encryptKey = rsa_cipher.rsaEncrypt(encryptKey_json)
    body = {
        "accessId": "000000000000000",
        "encryptKey": encryptKey,
        "sign": sign,
        "info": info,
        "reqTime": reqTime
    }
    data = {
        "body": str(body),
        "url": url
    }
    response = requests.post(url='https://interface.postwork.cn/admin/ruiyinxin/', data=data)
    response_data = response.json()
    reaponse_reqTime = response_data['reqTime']
    reaponse_encryptKey = json.loads(rsa_cipher.rsaDecrypt(response_data['encryptKey']))
    response_message = f'accessId={response_data["accessId"]}&reqTime={reaponse_reqTime}&ivParam={reaponse_encryptKey["ivParam"]}'
    response_aes_cipher = AESCipher(reaponse_encryptKey['aesKey'], reaponse_encryptKey['ivParam'])
    reaponse_info = json.loads(response_aes_cipher.decrypt(response_data['info']))
    return reaponse_info


def query_merinid(s_merInId):
    publicKey = '''MIIBI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vZZkrwfuaAH5Bewj/4Angqn/2f8SnH7ecWAwV8ULb80zlwZqIR37PEZw2Chq0SJCgh7y9VXfc8WmLPfNNX3U2MS8zJSxdgvvbMBtPiMlWf7L2H5TNLm/2yr0+iYK8DBV96RdxBwCkRnUatK4R25jA1Elr1a6cqw3hLAGhQKBgQC6WYY5nDE6YTKERk4ZfL4Up3TDWn31JgxhWpStIo0sevb57iepkG7JX3f8n81H4LI3j1lSyq4y+eKCJ+ZVOGVJFvgbBVzS8SVQybvKe3hX57x4aPhXDxVadlQQwHL2KBMoydc66m4Y6BylqeerRzL9fN1xVC183Si+2tnSOf05WwKBgCc+5EC2NUeE/x02JBoAdpi/0vZyJcgUMAYkD339P+ZsBzjpZQbq0HnHB5r21bbSlpdc2LL1MzQa+qWbGaJlQG2wL2e3foD3diEzOnGkMGUlly42OdjfYiySEWgAv7Bggej6dLEvu0Wl+Uvu+spaqVXVAA92V0pDqN+tkua8h7KBAoGAU4gHu9FA29tv6o0dOx2IkveRRnRM29PnXshcttMzFwozpUrU6pQ8pPWvckUrnpmhKXiPYKZLubv7hb5e6Dp0ZHPwWSRpPIEt6e3TyOrZwgW1nP/ouhWfy8IY4r1xitfh5rm7ScSF/5IkLTphB4zN1YTgOomyLjNwrUSquSqXUNsCgYEAx0Nbfq+AzCS3fgm3d0Rh2LMjzmr+SdJa6LVOPiRORl9g4kvUVo5oRmFTxMMgJFEu+2e1yKCzx9P8byN2X90ggHw64bnnfNtybFo7LWfK//CDWeF2pKCYFHLI2etr1in7NKpWe6TpGtfzQwc1cQG7dj3UEHhmL37qXu4hCsx0KDs='''
    url = 'https://rjp.ruiyinxin.com/nms/ims/merch/getMerInId'
    reqTime = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
    aesKey = random_str(43) + '='
    ivParam = random_str(16)
    encryptKey_json = json.dumps({"aesKey": aesKey, "ivParam": ivParam})
    aes_cipher = AESCipher(aesKey, ivParam)
    rsa_cipher = RSACipher(publicKey, aceessPrivateKey)
    info = aes_cipher.encrypt(json.dumps({"merId": s_merInId}))
    message = f'accessId=000000000000000&reqTime={reqTime}&ivParam={ivParam}&merId={s_merInId}'
    sign = rsa_cipher.sign(message)
    encryptKey = rsa_cipher.rsaEncrypt(encryptKey_json)
    body = {
        "accessId": "000000000000000",
        "encryptKey": encryptKey,
        "sign": sign,
        "info": info,
        "reqTime": reqTime
    }
    response = requests.post(url=url, data=body)
    response_data = response.json()
    reaponse_reqTime = response_data['reqTime']
    reaponse_encryptKey = json.loads(rsa_cipher.rsaDecrypt(response_data['encryptKey']))
    response_message = f'accessId={response_data["accessId"]}&reqTime={reaponse_reqTime}&ivParam={reaponse_encryptKey["ivParam"]}'
    response_aes_cipher = AESCipher(reaponse_encryptKey['aesKey'], reaponse_encryptKey['ivParam'])
    reaponse_info = json.loads(response_aes_cipher.decrypt(response_data['info']))
    return reaponse_info['result']['merInId']


def query_transettle(s_merInId, s_tranDates, s_tranDatee):
    '''
    publicKey 服务端公钥
    privateKey 服务端私钥
    accessPublicKey 客户端公钥
    aceessPrivateKey 客户端私钥
    '''
    publicKey = '''MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0CzGDOwz5IcPA+/EhLt98G7EKUhE90U1v162xqXDzL8t+2Ok+iBnZQFFqWNB6gnID7GzaUVrDaNQX1vFLcCvhCgMgvOa973xFjeDJPXF/xUQboagWkZb8EGxiyympbN8SO4mey9Ldn9EX3m+yKuqvCrJTEKK0Gqg/Y/Dr3oCzC8KdesAb6x/ZTccsyHVPrzZ5LUkIMFVb4QVAFcI6/aa3G4GpZwLdsxrUnJ1k8kjYgx0GfC6Z0M665Z+lZpt+bQjk/ZwEHkbAjleREz/DPiefBbfGP/UKgLjcRxTN8mPHzT1SHw1U8hV4zFyJkGAOL+b8Bg4LAuHwveoeMYmf3kGeQIDAQAB'''
    privateKey = '''MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDQLMYM7DPkhw8D78SEu33wbsQpS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u+spaqVXVAA92V0pDqN+tkua8h7KBAoGAU4gHu9FA29tv6o0dOx2IkveRRnRM29PnXshcttMzFwozpUrU6pQ8pPWvckUrnpmhKXiPYKZLubv7hb5e6Dp0ZHPwWSRpPIEt6e3TyOrZwgW1nP/ouhWfy8IY4r1xitfh5rm7ScSF/5IkLTphB4zN1YTgOomyLjNwrUSquSqXUNsCgYEAx0Nbfq+AzCS3fgm3d0Rh2LMjzmr+SdJa6LVOPiRORl9g4kvUVo5oRmFTxMMgJFEu+2e1yKCzx9P8byN2X90ggHw64bnnfNtybFo7LWfK//CDWeF2pKCYFHLI2etr1in7NKpWe6TpGtfzQwc1cQG7dj3UEHhmL37qXu4hCsx0KDs='''
    url = 'https://rjp.ruiyinxin.com/nms/ims/tranSt/tranStList'
    reqTime = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
    aesKey = random_str(43) + '='
    ivParam = random_str(16)
    encryptKey_json = json.dumps({"aesKey": aesKey, "ivParam": ivParam})
    aes_cipher = AESCipher(aesKey, ivParam)
    rsa_cipher = RSACipher(publicKey, aceessPrivateKey)
    info = aes_cipher.encrypt(json.dumps({"s_merInId": s_merInId, "s_tranDates": s_tranDates, "s_tranDatee": s_tranDatee}))
    message = f'accessId=000000000000000&reqTime={reqTime}&ivParam={ivParam}&s_merInId={s_merInId}&s_tranDatee={s_tranDatee}&s_tranDates={s_tranDates}'
    sign = rsa_cipher.sign(message)
    encryptKey = rsa_cipher.rsaEncrypt(encryptKey_json)
    body = {
        "accessId": "000000000000000",
        "encryptKey": encryptKey,
        "sign": sign,
        "info": info,
        "reqTime": reqTime
    }
    data = {
        "body": str(body),
        "url": url
    }
    response = requests.post(url='https://interface.postwork.cn/admin/ruiyinxin/', data=data)
    response_data = response.json()
    reaponse_reqTime = response_data['reqTime']
    reaponse_encryptKey = json.loads(rsa_cipher.rsaDecrypt(response_data['encryptKey']))
    response_message = f'accessId={response_data["accessId"]}&reqTime={reaponse_reqTime}&ivParam={reaponse_encryptKey["ivParam"]}'
    response_aes_cipher = AESCipher(reaponse_encryptKey['aesKey'], reaponse_encryptKey['ivParam'])
    reaponse_info = json.loads(response_aes_cipher.decrypt(response_data['info']))
    return reaponse_info


def synchronous_settlerecord():
    print('%s: synchronous_settlerecord' % time.ctime())
    date_now = datetime.datetime.now().strftime('%Y-%m-%d 00:00:00')
    queryset = MerchantChannel.objects.filter(merchant__merchantbill__bill_state__in=[1, 5], channel_id=2, merchant__merchantbill__receipts_time__lt=date_now).distinct()
    print('应结算商户数', len(queryset))
    # queryset = MerchantChannel.objects.filter(merchant_id=720)
    for query in queryset:
        merchant_id = query.merchant_id
        channel_mchid = query.channel_mchid
        result = query_transettletoday(channel_mchid)['result']
        # result = query_transettle(channel_mchid)['result']
        if result:
            result = result['list']
            for i in result:
                if i['settleType'] =='16':
                    if i['status'] == '出款中':
                        continue
                    settlement_time = datetime.datetime.strptime(str(i['settDate']), "%Y%m%d%H%M%S")
                    settlerecord_data = {}
                    settlerecord_data['merchant_id'] = merchant_id
                    settlerecord_data['account_name'] = i['cardName']
                    settlerecord_data['account_bank'] = i['bankName']
                    settlerecord_data['account_number'] = i['cardNo']
                    settlerecord_data['amount'] = i['amt']
                    settlerecord_data['settlement_time'] = settlement_time
                    settlerecord_data['fail_reason'] = i['failReason']
                    if i['status'] == '出款成功':
                        settlerecord_data['status'] = 3
                    elif i['status'] == '出款中':
                        settlerecord_data['status'] = 2
                    else:
                        settlerecord_data['status'] = 5
                    instance, create = MerchantSettlementRecord.objects.update_or_create(defaults=settlerecord_data, merchant_id=merchant_id, settlement_time=settlement_time)
                    if create:
                        # if i['status'] == '出款成功':
                        settlement_time_before = settlement_time + datetime.timedelta(days=-1)
                        merchantbill_set = MerchantBill.objects.filter(bill_state=1, merchant_id=merchant_id, receipts_time__lt=settlement_time_before)
                        for merchantbill in merchantbill_set:
                            relations_data = {}
                            relations_data['settlement_record_id'] = instance.id
                            relations_data['bill_id'] = merchantbill.id
                            MerchantBillSettlementRecord.objects.get_or_create(defaults=relations_data, settlement_record_id=instance.id, bill_id=merchantbill.id)
                            print(f'{merchantbill.id}正常结算:{i["status"]}')
                        merchantbill_set.update(
                            account_name=i['cardName'],
                            account_bank=i['bankName'],
                            account_number=i['cardNo'],
                            settlement_time=settlement_time,
                            settlement_record_id=instance.id,
                            bill_state=instance.status,
                        )
                elif i['settleType'] =='02':
                    if i['status'] == '出款中':
                        continue
                    settlement_time = datetime.datetime.strptime(str(i['settDate']), "%Y%m%d%H%M%S")
                    settlerecord_data = {}
                    settlerecord_data['merchant_id'] = merchant_id
                    settlerecord_data['account_name'] = i['cardName']
                    settlerecord_data['account_bank'] = i['bankName']
                    settlerecord_data['account_number'] = i['cardNo']
                    settlerecord_data['amount'] = i['amt']
                    settlerecord_data['settlement_time'] = settlement_time
                    settlerecord_data['fail_reason'] = i['failReason']
                    settlerecord_data['settle_type'] = 2
                    if i['status'] == '出款成功':
                        settlerecord_data['status'] = 3
                    elif i['status'] == '出款中':
                        settlerecord_data['status'] = 2
                    else:
                        settlerecord_data['status'] = 5
                    instance, create = MerchantSettlementRecord.objects.update_or_create(defaults=settlerecord_data, merchant_id=merchant_id, settlement_time=settlement_time)
                    if create:
                        # if i['status'] == '出款成功':
                        settlement_time_before = settlement_time + datetime.timedelta(days=-1)
                        merchantbill_set = MerchantBill.objects.filter(bill_state=5, merchant_id=merchant_id, receipts_time__lt=settlement_time_before)
                        for merchantbill in merchantbill_set:
                            relations_data = {}
                            relations_data['settlement_record_id'] = instance.id
                            relations_data['bill_id'] = merchantbill.id
                            MerchantBillSettlementRecord.objects.get_or_create(defaults=relations_data, settlement_record_id=instance.id, bill_id=merchantbill.id)
                            print(f'{merchantbill.id}退汇结算:{i["status"]}')
                        merchantbill_set.update(
                            account_name=i['cardName'],
                            account_bank=i['bankName'],
                            account_number=i['cardNo'],
                            settlement_time=settlement_time,
                            settlement_record_id=instance.id,
                            bill_state=instance.status,
                        )
    return '------------结束------------'


def check_try():
    instance = SpeedMerchantAuthDraw.objects.filter(appid='wx1cdf14a52b6b487b', platform=1, payment_status=1).update(payment_status=3)


def query_sxf_transettle(business_no, date_time):
    url = 'https://manage.gdwxyf.com/internal/searchmerchantpaidoutmsg.do'
    body = {
        "shop_id": business_no,
        "start": date_time,
        "end": date_time,
        "channel": "sxf_tq",
        "branch_id": "2",
        "type": "trueid"
    }
    response = requests.post(url=url, data=body)
    result = response.json()
    if result['result_code'] == 'success':
        return result['paidout_list']
    else:
        return []


def synchronous_settlerecord1():
    print('%s: synchronous_settlerecord1' % time.ctime())
    date_now = datetime.datetime.now().strftime('%Y-%m-%d 00:00:00')
    # queryset = MerchantChannel.objects.filter(merchant__merchantbill__bill_state=1, channel_id=2).distinct()
    queryset = MerchantBill.objects.filter(bill_state=1, receipts_time__gt='2023-02-05 00:00:00').order_by('receipts_time')
    print('应结算商户数', len(queryset))
    # queryset = MerchantChannel.objects.filter(merchant_id=720)
    for query in queryset:
        print(query.id)
        merchant_id = query.merchant_id
        channel_mchid = MerchantChannel.objects.filter(merchant_id=merchant_id, channel_id=2)
        if not channel_mchid:
            continue
        channel_mchid = channel_mchid.first().channel_mchid
        s_tranDates = (query.receipts_time + datetime.timedelta(days=1)).strftime("%Y%m%d")
        result = query_transettle(channel_mchid, s_tranDates, s_tranDates)['result']
        # result = query_transettle(channel_mchid)['result']
        if result:
            result = result['list']
            for i in result:
                if i['settleType'] in ['16', '10']:
                    if i['status'] == '出款中':
                        continue
                    settlement_time = datetime.datetime.strptime(str(i['settDate']), "%Y%m%d%H%M%S")
                    settlerecord_data = {}
                    settlerecord_data['merchant_id'] = merchant_id
                    settlerecord_data['account_name'] = i['cardName']
                    settlerecord_data['account_bank'] = i['bankName']
                    settlerecord_data['account_number'] = i['cardNo']
                    settlerecord_data['amount'] = i['amt']
                    settlerecord_data['settlement_time'] = settlement_time
                    settlerecord_data['fail_reason'] = i['failReason']
                    settlerecord_data['level_id'] = query.merchant.level_id
                    if i['status'] == '出款成功':
                        settlerecord_data['status'] = 3
                    elif i['status'] == '出款中':
                        settlerecord_data['status'] = 2
                    else:
                        settlerecord_data['status'] = 5
                    instance, create = MerchantSettlementRecord.objects.update_or_create(defaults=settlerecord_data, merchant_id=merchant_id, settlement_time=settlement_time)
                    if Decimal(str(instance.amount)) == query.payable_amount:
                        relations_data = {}
                        relations_data['settlement_record_id'] = instance.id
                        relations_data['bill_id'] = query.id
                        MerchantBillSettlementRecord.objects.get_or_create(defaults=relations_data, settlement_record_id=instance.id, bill_id=query.id)
                        print(f'{query.id}正常结算:{i["status"]}')
                        query.account_name = i['cardName']
                        query.account_bank = i['bankName']
                        query.account_number = i['cardNo']
                        query.settlement_time = settlement_time
                        query.settlement_record_id = instance.id
                        query.bill_state = instance.status
                        query.settlement_amount = instance.amount
                        query.save()
                        # if i['status'] == '出款成功':
                        # settlement_time_before = settlement_time + datetime.timedelta(days=-1)
                        # merchantbill_set = MerchantBill.objects.filter(bill_state=1, merchant_id=merchant_id, receipts_time__lt=settlement_time_before)
                        # for merchantbill in merchantbill_set:
                        #     relations_data = {}
                        #     relations_data['settlement_record_id'] = instance.id
                        #     relations_data['bill_id'] = merchantbill.id
                        #     MerchantBillSettlementRecord.objects.get_or_create(defaults=relations_data, settlement_record_id=instance.id, bill_id=merchantbill.id)
                        #     print(f'{merchantbill.id}正常结算:{i["status"]}')
                        # merchantbill_set.update(
                        #     account_name=i['cardName'],
                        #     account_bank=i['bankName'],
                        #     account_number=i['cardNo'],
                        #     settlement_time=settlement_time,
                        #     settlement_record_id=instance.id,
                        #     bill_state=instance.status,
                        # )
                elif i['settleType'] =='02':
                    if i['status'] == '出款中':
                        continue
                    settlement_time = datetime.datetime.strptime(str(i['settDate']), "%Y%m%d%H%M%S")
                    settlerecord_data = {}
                    settlerecord_data['merchant_id'] = merchant_id
                    settlerecord_data['account_name'] = i['cardName']
                    settlerecord_data['account_bank'] = i['bankName']
                    settlerecord_data['account_number'] = i['cardNo']
                    settlerecord_data['amount'] = i['amt']
                    settlerecord_data['settlement_time'] = settlement_time
                    settlerecord_data['fail_reason'] = i['failReason']
                    settlerecord_data['settle_type'] = 2
                    if i['status'] == '出款成功':
                        settlerecord_data['status'] = 3
                    elif i['status'] == '出款中':
                        settlerecord_data['status'] = 2
                    else:
                        settlerecord_data['status'] = 5
                    instance, create = MerchantSettlementRecord.objects.update_or_create(defaults=settlerecord_data, merchant_id=merchant_id, settlement_time=settlement_time)
                    if Decimal(str(instance.amount)) == query.payable_amount:
                        relations_data = {}
                        relations_data['settlement_record_id'] = instance.id
                        relations_data['bill_id'] = query.id
                        MerchantBillSettlementRecord.objects.get_or_create(defaults=relations_data, settlement_record_id=instance.id, bill_id=query.id)
                        print(f'{query.id}正常结算:{i["status"]}')
                        query.account_name = i['cardName']
                        query.account_bank = i['bankName']
                        query.account_number = i['cardNo']
                        query.settlement_time = settlement_time
                        query.settlement_record_id = instance.id
                        query.bill_state = instance.status
                        query.settlement_amount = instance.amount
                        query.save()
    return '------------结束------------'


def synchronous_settlerecord2():
    print('%s: synchronous_settlerecord1' % time.ctime())
    date_now = datetime.datetime.now().strftime('%Y-%m-%d 00:00:00')
    # queryset = MerchantChannel.objects.filter(merchant__merchantbill__bill_state=1, channel_id=2).distinct()
    queryset = MerchantBill.objects.filter(bill_state=1).order_by('receipts_time')
    print('应结算商户数', len(queryset))
    # queryset = MerchantChannel.objects.filter(merchant_id=720)
    for query in queryset:
        query = MerchantBill.objects.get(id=query.id)
        if query.bill_state != 1:
            continue
        print(query.id)
        merchant_id = query.merchant_id
        channel_mchid = MerchantChannel.objects.filter(merchant_id=merchant_id, channel_id=2)
        if not channel_mchid:
            continue
        channel_mchid = channel_mchid.first().channel_mchid
        days = 1
        while True:
            s_tranDates = (query.receipts_time + datetime.timedelta(days=days)).strftime("%Y%m%d")
            result = query_transettle(channel_mchid, s_tranDates, s_tranDates)['result']
            # result = query_transettle(channel_mchid)['result']
            if result:
                break
            # print(days)
            if days == 8:
                break
            days += 1
        if result:
            result = result['list']
            for i in result:
                if i['settleType'] in ['16', '10', '02']:
                    if i['status'] == '出款中':
                        continue
                    settlement_time = datetime.datetime.strptime(str(i['settDate']), "%Y%m%d%H%M%S")
                    settlerecord_data = {}
                    settlerecord_data['merchant_id'] = merchant_id
                    settlerecord_data['account_name'] = i['cardName']
                    settlerecord_data['account_bank'] = i['bankName']
                    settlerecord_data['account_number'] = i['cardNo']
                    settlerecord_data['amount'] = i['amt']
                    settlerecord_data['settlement_time'] = settlement_time
                    settlerecord_data['fail_reason'] = i['failReason']
                    settlerecord_data['level_id'] = query.merchant.level_id
                    settlerecord_data['channel_id'] = 2
                    if i['status'] == '出款成功':
                        settlerecord_data['status'] = 3
                    elif i['status'] == '出款中':
                        settlerecord_data['status'] = 2
                    else:
                        settlerecord_data['status'] = 5
                    instance, create = MerchantSettlementRecord.objects.update_or_create(defaults=settlerecord_data, merchant_id=merchant_id, settlement_time=settlement_time)
                    settlement_time_before = settlement_time + datetime.timedelta(days=-1)
                    receipts_time__gte = settlement_time + datetime.timedelta(days=-9)
                    merchantbill_set = MerchantBill.objects.filter(bill_state=1, merchant_id=merchant_id, receipts_time__lt=settlement_time_before, receipts_time__gte=receipts_time__gte)
                    total_amount = merchantbill_set.aggregate(Sum('payable_amount'))['payable_amount__sum']
                    if Decimal(str(instance.amount)) == total_amount:
                        for merchantbill in merchantbill_set:
                            relations_data = {}
                            relations_data['settlement_record_id'] = instance.id
                            relations_data['bill_id'] = merchantbill.id
                            MerchantBillSettlementRecord.objects.get_or_create(defaults=relations_data, settlement_record_id=instance.id, bill_id=merchantbill.id)
                            print(f'{merchantbill.id}正常结算:{i["status"]}')
                        merchantbill_set.update(
                            account_name=i['cardName'],
                            account_bank=i['bankName'],
                            account_number=i['cardNo'],
                            settlement_time=settlement_time,
                            settlement_record_id=instance.id,
                            bill_state=instance.status,
                            settlement_amount=instance.amount
                        )
                # elif i['settleType'] =='02':
                #     if i['status'] == '出款中':
                #         continue
                #     settlement_time = datetime.datetime.strptime(str(i['settDate']), "%Y%m%d%H%M%S")
                #     settlerecord_data = {}
                #     settlerecord_data['merchant_id'] = merchant_id
                #     settlerecord_data['account_name'] = i['cardName']
                #     settlerecord_data['account_bank'] = i['bankName']
                #     settlerecord_data['account_number'] = i['cardNo']
                #     settlerecord_data['amount'] = i['amt']
                #     settlerecord_data['settlement_time'] = settlement_time
                #     settlerecord_data['fail_reason'] = i['failReason']
                #     settlerecord_data['settle_type'] = 2
                #     if i['status'] == '出款成功':
                #         settlerecord_data['status'] = 3
                #     elif i['status'] == '出款中':
                #         settlerecord_data['status'] = 2
                #     else:
                #         settlerecord_data['status'] = 5
                #     instance, create = MerchantSettlementRecord.objects.update_or_create(defaults=settlerecord_data, merchant_id=merchant_id, settlement_time=settlement_time)
                #     if create:
                #         settlement_time_before = settlement_time + datetime.timedelta(days=-1)
                #         merchantbill_set = MerchantBill.objects.filter(bill_state=1, merchant_id=merchant_id, receipts_time__lt=settlement_time_before)
                #         total_amount = merchantbill_set.aggregate(Sum('payable_amount'))['payable_amount__sum']
                #         if instance.amount == total_amount:
                #             for merchantbill in merchantbill_set:
                #                 relations_data = {}
                #                 relations_data['settlement_record_id'] = instance.id
                #                 relations_data['bill_id'] = merchantbill.id
                #                 MerchantBillSettlementRecord.objects.get_or_create(defaults=relations_data, settlement_record_id=instance.id, bill_id=merchantbill.id)
                #                 print(f'{merchantbill.id}正常结算:{i["status"]}')
                #             merchantbill_set.update(
                #                 account_name=i['cardName'],
                #                 account_bank=i['bankName'],
                #                 account_number=i['cardNo'],
                #                 settlement_time=settlement_time,
                #                 settlement_record_id=instance.id,
                #                 bill_state=instance.status,
                #             )
    return '------------结束------------'


def synchronous_settlerecord3():
    print('%s: synchronous_settlerecord3' % time.ctime())
    # today = datetime.datetime.now() + datetime.timedelta(days=-5)
    today = datetime.datetime.now()
    print(today)
    weeks = today.weekday()
    receipts_time = (today + datetime.timedelta(days=-1)).strftime('%Y-%m-%d 00:00:00')
    queryset = MerchantBill.objects.filter(bill_state=1, receipts_time=receipts_time).order_by('receipts_time')
    receipts_time__gte = (today + datetime.timedelta(days=-3)).strftime('%Y-%m-%d 00:00:00')
    receipts_time__lte = (today + datetime.timedelta(days=-1)).strftime('%Y-%m-%d 00:00:00')
    if weeks == 0:
        ruiyinxin_queryset = MerchantBill.objects.filter(bill_state=1, receipts_time__gte=receipts_time__gte, receipts_time__lte=receipts_time__lte).order_by('receipts_time')
    else:
        ruiyinxin_queryset = queryset
    print('应结算商户数', len(queryset))
    for query in queryset:
        query = MerchantBill.objects.get(id=query.id)
        if query.bill_state != 1:
            continue
        business_no = query.merchant.wyfMerchantID
        merchant_id = query.merchant_id
        s_tranDates = (query.receipts_time + datetime.timedelta(days=1)).strftime("%Y-%m-%d")
        instance = MerchantSettlementRecord.objects.filter(merchant_id=merchant_id, settlement_time=f'{s_tranDates} 00:00:00').first()
        if instance:
            continue
        result = query_sxf_transettle(business_no, s_tranDates)
        if result:
            for i in result:
                settlement_time = datetime.datetime.strptime(str(i['date']), "%Y%m%d")
                total_amount = query.payable_amount
                if Decimal(str(i['paidout'])) == total_amount:
                    if i['status'] == '付款成功':
                        settlerecord_data = {}
                        settlerecord_data['merchant_id'] = merchant_id
                        settlerecord_data['account_name'] = i['card_name']
                        settlerecord_data['account_bank'] = '中国邮政储蓄银行总行'
                        settlerecord_data['account_number'] = i['card']
                        settlerecord_data['amount'] = i['money']
                        settlerecord_data['settlement_time'] = settlement_time
                        settlerecord_data['fail_reason'] = ''
                        settlerecord_data['level_id'] = query.merchant.level_id
                        settlerecord_data['channel_id'] = 3
                        if i['status'] == '付款成功':
                            settlerecord_data['status'] = 3
                        elif i['status'] == '付款中':
                            settlerecord_data['status'] = 2
                        else:
                            settlerecord_data['status'] = 5
                        instance, create = MerchantSettlementRecord.objects.update_or_create(defaults=settlerecord_data, merchant_id=merchant_id, settlement_time=settlement_time, amount=i['money'])
                        if instance.is_bind == 0:
                            relations_data = {}
                            relations_data['settlement_record_id'] = instance.id
                            relations_data['bill_id'] = query.id
                            MerchantBillSettlementRecord.objects.get_or_create(defaults=relations_data, settlement_record_id=instance.id, bill_id=query.id)
                            print(f'{query.id}正常结算:{i["status"]}')
                            query.account_name = i['card_name']
                            query.account_bank = '中国邮政储蓄银行总行'
                            query.account_number = i['card']
                            query.settlement_time = settlement_time
                            query.settlement_record_id = instance.id
                            query.bill_state = instance.status
                            query.settlement_amount = instance.amount
                            query.channel_id = 3
                            query.save()
                            instance.is_bind = 1
                            instance.save()

    # print('%s: synchronous_settlerecord4' % time.ctime())
    # receipts_time = (datetime.datetime.now() + datetime.timedelta(days=-1)).strftime('%Y-%m-%d 00:00:00')
    # queryset = MerchantBill.objects.filter(bill_state=1, receipts_time=receipts_time).order_by('receipts_time')
    # print('应结算商户数', len(queryset))
    for query in ruiyinxin_queryset:
        query = MerchantBill.objects.get(id=query.id)
        if query.bill_state != 1:
            continue
        print(query.id)
        merchant_id = query.merchant_id
        channel_mchid = MerchantChannel.objects.filter(merchant_id=merchant_id, channel_id=2)
        if not channel_mchid:
            continue
        channel_mchid = channel_mchid.first().channel_mchid
        if weeks == 0:
            if query.receipts_time.weekday() == 4:
                s_tranDates = (query.receipts_time + datetime.timedelta(days=3)).strftime("%Y%m%d")
                result = query_transettle(channel_mchid, s_tranDates, s_tranDates)['result']
            elif query.receipts_time.weekday() == 5:
                s_tranDates = (query.receipts_time + datetime.timedelta(days=2)).strftime("%Y%m%d")
                result = query_transettle(channel_mchid, s_tranDates, s_tranDates)['result']
            else:
                s_tranDates = (query.receipts_time + datetime.timedelta(days=1)).strftime("%Y%m%d")
                result = query_transettle(channel_mchid, s_tranDates, s_tranDates)['result']
        else:
            s_tranDates = (query.receipts_time + datetime.timedelta(days=1)).strftime("%Y%m%d")
            result = query_transettle(channel_mchid, s_tranDates, s_tranDates)['result']
        result_list = []
        if result:
            result_list += result['list']
        result = query_transettletoday(channel_mchid)['result']
        if result:
            result_list += result['list']
        for i in result_list:
            try:
                if i['settleType'] in ['16', '10']:
                    if i['status'] == '出款中':
                        continue
                    settlement_time = datetime.datetime.strptime(str(i['settDate']), "%Y%m%d%H%M%S")
                    settlerecord_data = {}
                    settlerecord_data['merchant_id'] = merchant_id
                    settlerecord_data['account_name'] = i['cardName']
                    settlerecord_data['account_bank'] = i['bankName']
                    settlerecord_data['account_number'] = i['cardNo']
                    settlerecord_data['amount'] = i['amt']
                    settlerecord_data['settlement_time'] = settlement_time
                    settlerecord_data['fail_reason'] = i['failReason']
                    settlerecord_data['level_id'] = query.merchant.level_id
                    settlerecord_data['channel_id'] = 2
                    if i['status'] == '出款成功':
                        settlerecord_data['status'] = 3
                    elif i['status'] == '出款中':
                        settlerecord_data['status'] = 2
                    else:
                        settlerecord_data['status'] = 5
                    instance, create = MerchantSettlementRecord.objects.get_or_create(defaults=settlerecord_data, merchant_id=merchant_id, settlement_time=settlement_time)
                    if instance.is_bind == 0:
                        if settlement_time.weekday() == 0:
                            merchantbill_set = MerchantBill.objects.filter(bill_state=1, merchant_id=merchant_id, receipts_time__lte=receipts_time__lte, receipts_time__gte=receipts_time__gte)
                            total_amount = merchantbill_set.aggregate(Sum('payable_amount'))['payable_amount__sum']
                            if Decimal(str(instance.amount)) == total_amount:
                                for merchantbill in merchantbill_set:
                                    relations_data = {}
                                    relations_data['settlement_record_id'] = instance.id
                                    relations_data['bill_id'] = merchantbill.id
                                    MerchantBillSettlementRecord.objects.get_or_create(defaults=relations_data, settlement_record_id=instance.id, bill_id=merchantbill.id)
                                    print(f'{merchantbill.id}正常结算:{i["status"]}')
                                merchantbill_set.update(
                                    account_name=i['cardName'],
                                    account_bank=i['bankName'],
                                    account_number=i['cardNo'],
                                    settlement_time=settlement_time,
                                    settlement_record_id=instance.id,
                                    bill_state=instance.status,
                                    settlement_amount=instance.amount,
                                    channel_id=2
                                )
                                instance.is_bind = 1
                                instance.save()
                        else:
                            if Decimal(str(instance.amount)) == query.payable_amount:
                                relations_data = {}
                                relations_data['settlement_record_id'] = instance.id
                                relations_data['bill_id'] = query.id
                                MerchantBillSettlementRecord.objects.get_or_create(defaults=relations_data, settlement_record_id=instance.id, bill_id=query.id)
                                print(f'{query.id}正常结算:{i["status"]}')
                                query.account_name = i['cardName']
                                query.account_bank = i['bankName']
                                query.account_number = i['cardNo']
                                query.settlement_time = settlement_time
                                query.settlement_record_id = instance.id
                                query.bill_state = instance.status
                                query.settlement_amount = instance.amount
                                query.channel_id = 2
                                query.save()
                                instance.is_bind = 1
                                instance.save()
                elif i['settleType'] =='02':
                    if i['status'] == '出款中':
                        continue
                    settlement_time = datetime.datetime.strptime(str(i['settDate']), "%Y%m%d%H%M%S")
                    settlerecord_data = {}
                    settlerecord_data['merchant_id'] = merchant_id
                    settlerecord_data['account_name'] = i['cardName']
                    settlerecord_data['account_bank'] = i['bankName']
                    settlerecord_data['account_number'] = i['cardNo']
                    settlerecord_data['amount'] = i['amt']
                    settlerecord_data['settlement_time'] = settlement_time
                    settlerecord_data['fail_reason'] = i['failReason']
                    settlerecord_data['settle_type'] = 2
                    settlerecord_data['level_id'] = query.merchant.level_id
                    settlerecord_data['channel_id'] = 2
                    if i['status'] == '出款成功':
                        settlerecord_data['status'] = 3
                    elif i['status'] == '出款中':
                        settlerecord_data['status'] = 2
                    else:
                        settlerecord_data['status'] = 5
                    instance, create = MerchantSettlementRecord.objects.get_or_create(defaults=settlerecord_data, merchant_id=merchant_id, settlement_time=settlement_time)
                    if instance.is_bind == 0:
                        if settlement_time.weekday() == 0:
                            merchantbill_set = MerchantBill.objects.filter(bill_state=1, merchant_id=merchant_id,
                                                                           receipts_time__lte=receipts_time__lte,
                                                                           receipts_time__gte=receipts_time__gte)
                            total_amount = merchantbill_set.aggregate(Sum('payable_amount'))['payable_amount__sum']
                            if Decimal(str(instance.amount)) == total_amount:
                                for merchantbill in merchantbill_set:
                                    relations_data = {}
                                    relations_data['settlement_record_id'] = instance.id
                                    relations_data['bill_id'] = merchantbill.id
                                    MerchantBillSettlementRecord.objects.get_or_create(defaults=relations_data,
                                                                                       settlement_record_id=instance.id,
                                                                                       bill_id=merchantbill.id)
                                    print(f'{merchantbill.id}正常结算:{i["status"]}')
                                merchantbill_set.update(
                                    account_name=i['cardName'],
                                    account_bank=i['bankName'],
                                    account_number=i['cardNo'],
                                    settlement_time=settlement_time,
                                    settlement_record_id=instance.id,
                                    bill_state=instance.status,
                                    settlement_amount=instance.amount,
                                    channel_id=2
                                )
                                instance.is_bind = 1
                                instance.save()
                        else:
                            if Decimal(str(instance.amount)) == query.payable_amount:
                                relations_data = {}
                                relations_data['settlement_record_id'] = instance.id
                                relations_data['bill_id'] = query.id
                                MerchantBillSettlementRecord.objects.get_or_create(defaults=relations_data, settlement_record_id=instance.id, bill_id=query.id)
                                print(f'{query.id}正常结算:{i["status"]}')
                                query.account_name = i['cardName']
                                query.account_bank = i['bankName']
                                query.account_number = i['cardNo']
                                query.settlement_time = settlement_time
                                query.settlement_record_id = instance.id
                                query.bill_state = instance.status
                                query.settlement_amount = instance.amount
                                query.channel_id = 2
                                query.save()
                                instance.is_bind = 1
                                instance.save()
            except Exception as e:
                print(f'{merchant_id}错误')

    return '------------结束------------'


def synchronous_settlerecord4():
    print('%s: synchronous_settlerecord4' % time.ctime())
    receipts_time = (datetime.datetime.now() + datetime.timedelta(days=-2)).strftime('%Y-%m-%d 00:00:00')
    queryset = MerchantBill.objects.filter(bill_state=1, receipts_time=receipts_time).order_by('receipts_time')
    print('应结算商户数', len(queryset))
    for query in queryset:
        print(query.id)
        merchant_id = query.merchant_id
        channel_mchid = MerchantChannel.objects.filter(merchant_id=merchant_id, channel_id=2)
        if not channel_mchid:
            continue
        channel_mchid = channel_mchid.first().channel_mchid
        s_tranDates = (query.receipts_time + datetime.timedelta(days=1)).strftime("%Y%m%d")
        result = query_transettle(channel_mchid, s_tranDates, s_tranDates)['result']
        if result:
            result = result['list']
            for i in result:
                if i['settleType'] in ['16', '10']:
                    if i['status'] == '出款中':
                        continue
                    settlement_time = datetime.datetime.strptime(str(i['settDate']), "%Y%m%d%H%M%S")
                    settlerecord_data = {}
                    settlerecord_data['merchant_id'] = merchant_id
                    settlerecord_data['account_name'] = i['cardName']
                    settlerecord_data['account_bank'] = i['bankName']
                    settlerecord_data['account_number'] = i['cardNo']
                    settlerecord_data['amount'] = i['amt']
                    settlerecord_data['settlement_time'] = settlement_time
                    settlerecord_data['fail_reason'] = i['failReason']
                    settlerecord_data['level_id'] = query.merchant.level_id
                    settlerecord_data['channel_id'] = 2
                    if i['status'] == '出款成功':
                        settlerecord_data['status'] = 3
                    elif i['status'] == '出款中':
                        settlerecord_data['status'] = 2
                    else:
                        settlerecord_data['status'] = 5
                    instance, create = MerchantSettlementRecord.objects.update_or_create(defaults=settlerecord_data, merchant_id=merchant_id, settlement_time=settlement_time)
                    if instance.is_bind == 0:
                        if Decimal(str(instance.amount)) == query.payable_amount:
                            relations_data = {}
                            relations_data['settlement_record_id'] = instance.id
                            relations_data['bill_id'] = query.id
                            MerchantBillSettlementRecord.objects.get_or_create(defaults=relations_data, settlement_record_id=instance.id, bill_id=query.id)
                            print(f'{query.id}正常结算:{i["status"]}')
                            query.account_name = i['cardName']
                            query.account_bank = i['bankName']
                            query.account_number = i['cardNo']
                            query.settlement_time = settlement_time
                            query.settlement_record_id = instance.id
                            query.bill_state = instance.status
                            query.settlement_amount = instance.amount
                            query.channel_id = 2
                            query.save()
                            instance.is_bind = 1
                            instance.save()
                elif i['settleType'] =='02':
                    if i['status'] == '出款中':
                        continue
                    settlement_time = datetime.datetime.strptime(str(i['settDate']), "%Y%m%d%H%M%S")
                    settlerecord_data = {}
                    settlerecord_data['merchant_id'] = merchant_id
                    settlerecord_data['account_name'] = i['cardName']
                    settlerecord_data['account_bank'] = i['bankName']
                    settlerecord_data['account_number'] = i['cardNo']
                    settlerecord_data['amount'] = i['amt']
                    settlerecord_data['settlement_time'] = settlement_time
                    settlerecord_data['fail_reason'] = i['failReason']
                    settlerecord_data['settle_type'] = 2
                    settlerecord_data['level_id'] = query.merchant.level_id
                    settlerecord_data['channel_id'] = 2
                    if i['status'] == '出款成功':
                        settlerecord_data['status'] = 3
                    elif i['status'] == '出款中':
                        settlerecord_data['status'] = 2
                    else:
                        settlerecord_data['status'] = 5
                    instance, create = MerchantSettlementRecord.objects.update_or_create(defaults=settlerecord_data, merchant_id=merchant_id, settlement_time=settlement_time)
                    if instance.is_bind == 0:
                        if Decimal(str(instance.amount)) == query.payable_amount:
                            relations_data = {}
                            relations_data['settlement_record_id'] = instance.id
                            relations_data['bill_id'] = query.id
                            MerchantBillSettlementRecord.objects.get_or_create(defaults=relations_data, settlement_record_id=instance.id, bill_id=query.id)
                            print(f'{query.id}正常结算:{i["status"]}')
                            query.account_name = i['cardName']
                            query.account_bank = i['bankName']
                            query.account_number = i['cardNo']
                            query.settlement_time = settlement_time
                            query.settlement_record_id = instance.id
                            query.bill_state = instance.status
                            query.settlement_amount = instance.amount
                            query.save()
                            instance.is_bind = 1
                            instance.save()
    return '------------结束------------'


def synchronous_settlerecord5():
    queryset = MerchantSettlementRecord.objects.filter(is_bind=0, settlement_time__contains='2023-02-13', status=3)
    receipts_time__gte = '2023-02-07 00:00:00'
    receipts_time__lte = '2023-02-08 23:59:59'
    for query in queryset:
        merchantbill_set = MerchantBill.objects.filter(bill_state=1, merchant_id=query.merchant_id,
                                                       receipts_time__lte=receipts_time__lte,
                                                       receipts_time__gte=receipts_time__gte)
        total_amount = merchantbill_set.aggregate(Sum('payable_amount'))['payable_amount__sum']
        if Decimal(str(query.amount)) == total_amount:
            for merchantbill in merchantbill_set:
                relations_data = {}
                relations_data['settlement_record_id'] = query.id
                relations_data['bill_id'] = merchantbill.id
                MerchantBillSettlementRecord.objects.get_or_create(defaults=relations_data,
                                                                   settlement_record_id=query.id,
                                                                   bill_id=merchantbill.id)
                print(f'{merchantbill.id}正常结算:{query.status}')
            merchantbill_set.update(
                account_name=query.account_name,
                account_bank=query.account_bank,
                account_number=query.account_number,
                settlement_time=query.settlement_time,
                settlement_record_id=query.id,
                bill_state=query.status,
                settlement_amount=query.amount,
                channel_id=query.channel_id
            )
            query.is_bind = 1
            query.save()
    print(len(queryset))


def synchronization_settlementrecord_aaaaa(merchant_id):
    start_time = '2023-02-01'
    end_time = '2023-02-28'
    merchant = Merchant.objects.get(id=merchant_id)
    channel_mchid = MerchantChannel.objects.filter(merchant_id=merchant_id, channel_id=2)
    if channel_mchid:
        channel_mchid = channel_mchid.first().channel_mchid
        s_tranDates =datetime.datetime.strptime(start_time, "%Y-%m-%d").strftime("%Y%m%d")
        s_tranDatee = datetime.datetime.strptime(end_time, "%Y-%m-%d").strftime("%Y%m%d")
        result = query_transettle(channel_mchid, s_tranDates, s_tranDatee)['result']
        if result:
            result = result['list']
            for i in result:
                if i['settleType'] in ['16', '10', '02']:
                    if i['status'] == '出款中':
                        continue
                    settlement_time = datetime.datetime.strptime(str(i['settDate']), "%Y%m%d%H%M%S")
                    settlerecord_data = {}
                    settlerecord_data['merchant_id'] = merchant_id
                    settlerecord_data['account_name'] = i['cardName']
                    settlerecord_data['account_bank'] = i['bankName']
                    settlerecord_data['account_number'] = i['cardNo']
                    settlerecord_data['amount'] = i['amt']
                    settlerecord_data['settlement_time'] = settlement_time
                    settlerecord_data['fail_reason'] = i['failReason']
                    settlerecord_data['level_id'] = merchant.level_id
                    settlerecord_data['channel_id'] = 2
                    if i['status'] == '出款成功':
                        settlerecord_data['status'] = 3
                    elif i['status'] == '出款中':
                        settlerecord_data['status'] = 2
                    else:
                        settlerecord_data['status'] = 5
                    instance, create = MerchantSettlementRecord.objects.update_or_create(defaults=settlerecord_data, merchant_id=merchant_id, settlement_time=settlement_time)
    business_no = merchant.wyfMerchantID
    s_tranDates = datetime.datetime.strptime(start_time, "%Y-%m-%d")
    s_tranDatee = datetime.datetime.strptime(end_time, "%Y-%m-%d")
    while True:
        if s_tranDates > s_tranDatee:
            break
        instance = MerchantSettlementRecord.objects.filter(merchant_id=merchant_id, settlement_time=f'{s_tranDates.strftime("%Y-%m-%d 00:00:00")}').first()
        if instance:
            s_tranDates = s_tranDates + datetime.timedelta(days=1)
            continue
        # time.sleep(0.5)
        result = query_sxf_transettle(business_no, s_tranDates.strftime("%Y-%m-%d"))
        if result:
            for i in result:
                if i['status'] == '付款成功':
                    url = 'https://manage.gdwxyf.com/internal/searchorders.do'
                    body = {
                        'shopId': business_no,
                        'channel': 'sxf_tq',
                        'start': (s_tranDates + datetime.timedelta(days=-1)).strftime("%Y-%m-%d 00:00:00"),
                        'end': (s_tranDates + datetime.timedelta(days=-1)).strftime("%Y-%m-%d 23:59:59"),
                        'orderStatus': 'all',
                        'orderType': 'all',
                        'payType': 'all',
                        'agentId': 'all',
                        'branchId': '2',
                        'account': 'gdyouzheng'
                    }
                    response = requests.post(url=url, data=body).json()
                    if i['paidout'] == response['statistics']['paidoutMoney'] or (i['paidout']+i['commission']) == response['statistics']['paidoutMoney']:
                        continue
                    settlement_time = datetime.datetime.strptime(str(i['date']), "%Y%m%d")
                    settlerecord_data = {}
                    settlerecord_data['merchant_id'] = merchant_id
                    settlerecord_data['account_name'] = i['card_name']
                    settlerecord_data['account_bank'] = '中国邮政储蓄银行总行'
                    settlerecord_data['account_number'] = i['card']
                    settlerecord_data['amount'] = i['money']
                    settlerecord_data['settlement_time'] = settlement_time
                    settlerecord_data['fail_reason'] = ''
                    settlerecord_data['level_id'] = merchant.level_id
                    settlerecord_data['channel_id'] = 3
                    if i['status'] == '付款成功':
                        settlerecord_data['status'] = 3
                    elif i['status'] == '付款中':
                        settlerecord_data['status'] = 2
                    else:
                        settlerecord_data['status'] = 5
                    instance, create = MerchantSettlementRecord.objects.update_or_create(defaults=settlerecord_data, merchant_id=merchant_id, settlement_time=settlement_time)
        s_tranDates = s_tranDates + datetime.timedelta(days=1)
    return '导入成功'


def create_contract_table(merchant_name, merchant_other_5, artifIdentity, licenceNo):
    pdf = FPDF()
    pdf.add_page()
    fname = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), f'static/fonts/LXGWNeoZhiSongCHS.ttf')
    pdf.add_font('LXGWNeoZhiSongCHS', style='', fname=fname, uni=True)
    pdf.set_font("LXGWNeoZhiSongCHS", size=18)
    pdf.cell(w=190, h=10, txt='', border=0, ln=1, align="C")
    pdf.cell(w=190, h=10, txt='', border=0, ln=1, align="C")
    pdf.cell(w=190, h=10, txt='分账业务情况说明函', border=0, ln=1, align="C")
    pdf.cell(w=190, h=10, txt='', border=0, ln=1, align="C")
    pdf.set_font("LXGWNeoZhiSongCHS", size=13)
    pdf.cell(w=25, h=10, txt='', border=0, ln=0, align="C")
    pdf.cell(w=165, h=10, txt='致随行付支付有限公司：', border=0, ln=1, align="L")
    pdf.cell(w=25, h=10, txt='', border=0, ln=0, align="C")
    pdf.cell(w=15, h=10, txt='', border=0, ln=0, align="C")
    pdf.cell(w=35, h=10, txt='申请被分账方：', border=0, ln=0, align="L")
    pdf.set_font("LXGWNeoZhiSongCHS", size=13, style='U')
    pdf.cell(w=90, h=10, txt=f'{merchant_name}{merchant_other_5},', border=0, ln=1, align="L")
    pdf.set_font("LXGWNeoZhiSongCHS", size=13)
    pdf.cell(w=25, h=10, txt='', border=0, ln=0, align="C")
    pdf.cell(w=35, h=10, txt='法人身份证号：', border=0, ln=0, align="L")
    pdf.set_font("LXGWNeoZhiSongCHS", size=13, style='U')
    pdf.cell(w=105, h=10, txt=f'{artifIdentity}                                    ,', border=0, ln=1, align="L")
    pdf.set_font("LXGWNeoZhiSongCHS", size=13)
    pdf.cell(w=25, h=10, txt='', border=0, ln=0, align="C")
    pdf.cell(w=30, h=10, txt='营业执照号：', border=0, ln=0, align="L")
    pdf.set_font("LXGWNeoZhiSongCHS", size=13, style='U')
    pdf.cell(w=110, h=10, txt=f'{licenceNo}                                        ,', border=0, ln=1, align="L")
    pdf.set_font("LXGWNeoZhiSongCHS", size=13)
    pdf.cell(w=25, h=10, txt='', border=0, ln=0, align="C")
    pdf.cell(w=52, h=10, txt='我司的业务场景需求为', border=0, ln=0, align="L")
    pdf.set_font("LXGWNeoZhiSongCHS", size=13, style='U')
    pdf.cell(w=88, h=10, txt='    需求管理方与入驻方商户商品分销业务 ,', border=0, ln=1, align="C")
    pdf.set_font("LXGWNeoZhiSongCHS", size=13)
    pdf.cell(w=25, h=10, txt='', border=0, ln=0, align="C")
    pdf.cell(w=140, h=10, txt='各方约定通过分账功能实现场景需求。', border=0, ln=1, align="L")
    pdf.cell(w=25, h=10, txt='', border=0, ln=0, align="C")
    pdf.cell(w=15, h=10, txt='', border=0, ln=0, align="C")
    pdf.cell(w=125, h=10, txt='分账规则如下：', border=0, ln=1, align="L")
    pdf.cell(w=25, h=10, txt='', border=0, ln=0, align="C")
    pdf.cell(w=15, h=10, txt='', border=0, ln=0, align="C")
    pdf.cell(w=30, h=10, txt='分账接收方：', border=0, ln=0, align="L")
    pdf.set_font("LXGWNeoZhiSongCHS", size=13, style='U')
    pdf.cell(w=95, h=10, txt='广州上邑网络科技有限公司836581773990590,', border=0, ln=1, align="L")
    pdf.set_font("LXGWNeoZhiSongCHS", size=13)
    pdf.cell(w=25, h=10, txt='', border=0, ln=0, align="C")
    pdf.cell(w=15, h=10, txt='', border=0, ln=0, align="C")
    pdf.cell(w=25, h=10, txt='分账比例：', border=0, ln=0, align="L")
    pdf.set_font("LXGWNeoZhiSongCHS", size=13, style='U')
    pdf.cell(w=100, h=10, txt='      1%（具体比例以实际业务账单为准）       ,', border=0, ln=1, align="C")
    pdf.set_font("LXGWNeoZhiSongCHS", size=13)
    pdf.cell(w=25, h=10, txt='', border=0, ln=0, align="C")
    pdf.cell(w=15, h=10, txt='', border=0, ln=0, align="C")
    pdf.cell(w=45, h=10, txt='与被分账方合作关系为：', border=0, ln=0, align="L")
    pdf.set_font("LXGWNeoZhiSongCHS", size=13, style='U')
    pdf.cell(w=80, h=10, txt='          管理方和入驻商户           ;', border=0, ln=1, align="C")
    pdf.set_font("LXGWNeoZhiSongCHS", size=13)
    pdf.cell(w=25, h=10, txt='', border=0, ln=0, align="C")
    pdf.cell(w=15, h=10, txt='', border=0, ln=0, align="C")
    pdf.cell(w=125, h=10, txt='我司承诺：以上分账方与分账接收方均以真实业务往来为基础，', border=0, ln=1, align="L")
    pdf.cell(w=25, h=10, txt='', border=0, ln=0, align="C")
    pdf.cell(w=140, h=10, txt='我司对以上商户真实性以及其开展业务的合法合规性负责。我司授权', border=0, ln=1, align="L")
    pdf.cell(w=25, h=10, txt='', border=0, ln=0, align="C")
    pdf.cell(w=8, h=10, txt='由', border=0, ln=0, align="L")
    pdf.set_font("LXGWNeoZhiSongCHS", size=13, style='U')
    pdf.cell(w=62, h=10, txt='  广东省邮政广告有限公司  ', border=0, ln=0, align="C")
    pdf.set_font("LXGWNeoZhiSongCHS", size=13)
    pdf.cell(w=70, h=10, txt='向贵司发送分账指令，贵司只需根', border=0, ln=1, align="R")
    pdf.cell(w=25, h=10, txt='', border=0, ln=0, align="C")
    pdf.cell(w=140, h=10, txt='据相关指令发起分账，由此引发的一切法律责任、纠纷（包括不限于', border=0, ln=1, align="L")
    pdf.cell(w=25, h=10, txt='', border=0, ln=0, align="C")
    pdf.cell(w=140, h=10, txt='因从事违法行为而应当承担的法律责任）及造成的损失将由我司独立', border=0, ln=1, align="L")
    pdf.cell(w=25, h=10, txt='', border=0, ln=0, align="C")
    pdf.cell(w=140, h=10, txt='承担全部责任。', border=0, ln=1, align="L")
    pdf.cell(w=190, h=10, txt='', border=0, ln=1, align="C")
    pdf.cell(w=25, h=10, txt='', border=0, ln=0, align="C")
    pdf.cell(w=165, h=10, txt='被分账方签字盖章：', border=0, ln=1, align="C")
    pdf.cell(w=25, h=10, txt='', border=0, ln=0, align="C")
    pdf.cell(w=165, h=10, txt='日期：', border=0, ln=1, align="C")
    file_name = f"{merchant_name}{'%06d' % randint(0, 999999)}.pdf"
    path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), f'static/{merchant_name}.pdf')
    pdf.output(path)
    with open(path, 'rb') as f:
        result = f.read()
    pic_upload(result, file_name)
    os.remove(path)
    return file_name


def get_wyf_order(shopId, start, end):
    '''获取指定时间商户交易'''
    url = 'https://manage.gdwxyf.com/internal/searchorders.do'
    body = {}
    body['shopId'] = shopId
    body['start'] = start
    body['end'] = end
    body['orderStatus'] = '1'
    body['channel'] = 'all'
    body['orderType'] = 'all'
    body['payType'] = 'all'
    body['agentId'] = 'all'
    body['branchId'] = '2'
    body['account'] = 'gdyouzheng'
    response = requests.post(url=url, data=body)
    result = response.json()
    if 'showList' in result:
        showList = result['showList']
        for show in showList:
            if show['totalNormal'] >= 2:
                return show
        return {}
    else:
        return {}


def get_wyf_order_settle(shopId, start, end):
    '''获取指定时间商户交易金额'''
    url = 'https://manage.gdwxyf.com/internal/searchorders.do'
    body = {}
    body['shopId'] = shopId
    body['start'] = start
    body['end'] = end
    body['orderStatus'] = '1'
    body['channel'] = 'all'
    body['orderType'] = 'all'
    body['payType'] = 'all'
    body['agentId'] = 'all'
    body['branchId'] = '2'
    body['account'] = 'gdyouzheng'
    response = requests.post(url=url, data=body)
    result = response.json()
    if 'statistics' in result:
        statistics = result['statistics']
        return statistics['paidoutMoney']
    else:
        return 0


# def get_nfc_trade_zfb():
#     '''抓取碰一下交易数据'''
#     url = 'https://api.sutpay.com/admin/hand_movement/?id=2'
#     response = requests.get(url=url)
#     time.sleep(100)
#     channel = Channel.objects.get(id=14)
#     exportTradeInfo_url = 'https://devicedata.alipay.com/devicedata/open/nfc/monitor/exportTradeInfo'
#     body = {"pageNo": 1, "pageSize": 20}
#     headers = {
#         "Cookie": channel.cookie,
#         "referer": "https://b.alipay.com/",
#         "Content-Type": "application/json"
#     }
#     response = requests.post(url=exportTradeInfo_url, data=json.dumps(body), headers=headers)
#     result = response.json()
#     print(result)
#     a = 1
#     sql = ''
#     if 'code'in result and result['code'] == 'SUCCESS':
#         id = result['data']['id']
#         print(id)
#         deviceDownloadTask_url = 'https://devicedata.alipay.com/devicedata/open/downloadTask/deviceDownloadTask'
#         while True:
#             time.sleep(10)
#             if a > 30:
#                 break
#             a += 1
#             response = requests.get(deviceDownloadTask_url, headers=headers)
#             result = response.json()
#             if 'code' in result and result['code'] == 'SUCCESS':
#                 lists = result['data']['list']
#                 for i in lists:
#                     if i['id'] == id and i['url']:
#                         response = requests.get(i['url'])
#                         wb = xlrd.open_workbook(filename=None, file_contents=response.content)
#                         table = wb.sheets()[0]
#                         nrows = table.nrows
#                         sql = f'''INSERT INTO tb_merchant_nfc_device_trade(sn,device_type,store_name,province,city,district,address,transaction_id,trade_type,total_amount,trade_amount,trade_time) VALUES '''
#                         for i in range(1, nrows):
#                             rowValues = table.row_values(i)
#                             sql += str(tuple(rowValues))
#                             sql += ','
#                         sql = sql[:-1]
#                         sql += ';'
#                         a = 40
#                         break
#     if sql:
#         conn = pymysql.connect(host=settings.DATABASES['default']['HOST'],
#                                port=settings.DATABASES['default']['PORT'],
#                                database=settings.DATABASES['default']['NAME'],
#                                user=settings.DATABASES['default']['USER'],
#                                password=settings.DATABASES['default']['PASSWORD'])
#         cursor = conn.cursor(cursor=pymysql.cursors.SSDictCursor)
#         try:
#             cursor.execute(sql)
#             conn.commit()
#         except Exception as e:
#             print(e)
#             conn.rollback()
#         sql = 'UPDATE tb_merchant_nfc_device,tb_merchant_nfc_device_trade SET tb_merchant_nfc_device_trade.merchant_id=tb_merchant_nfc_device.merchant_id WHERE tb_merchant_nfc_device_trade.merchant_id IS NULL AND tb_merchant_nfc_device_trade.sn=tb_merchant_nfc_device.sn;'
#         try:
#             cursor.execute(sql)
#             conn.commit()
#         except:
#             conn.rollback()
#         cursor.close()
#         conn.close()
#         get_nfc_merchant()
#         get_nfc_trade_paytype2()
#         get_nfc_trade_paytype1()
#     print(sql)


def get_nfc_merchant():
    '''ncf设备对应商户'''
    conn = pymysql.connect(host=settings.DATABASES['default']['HOST'],
                           port=settings.DATABASES['default']['PORT'],
                           database=settings.DATABASES['default']['NAME'],
                           user=settings.DATABASES['default']['USER'],
                           password=settings.DATABASES['default']['PASSWORD'])
    cursor = conn.cursor(cursor=pymysql.cursors.SSDictCursor)
    sql = 'SELECT sn FROM tb_merchant_nfc_device_trade WHERE sn NOT IN (SELECT sn FROM tb_merchant_nfc_device) GROUP BY sn;'
    cursor.execute(sql)
    rows = cursor.fetchall()
    if rows:
        sql = f'''INSERT INTO tb_merchant_nfc_device (sn) VALUES '''
        for row in rows:
            sql += f'("{row["sn"]}"),'
        sql = sql[:-1]
        sql += ';'
        print(sql)
        try:
            cursor.execute(sql)
            conn.commit()
        except:
            conn.rollback()
    sql = 'UPDATE tb_merchant_nfc_device_trade,tb_merchant SET tb_merchant_nfc_device_trade.level_id=tb_merchant.level_id WHERE tb_merchant_nfc_device_trade.level_id IS NULL AND tb_merchant_nfc_device_trade.merchant_id=tb_merchant.id;'
    try:
        cursor.execute(sql)
        conn.commit()
    except:
        conn.rollback()
    cursor.close()
    conn.close()
    queryset = MerchantNFCDevice.objects.filter(merchant_id__isnull=True)
    url = 'https://manage.gdwxyf.com/internal/searchqrcode.do'
    for query in queryset:
        body = {
            "simpleCodeId": query.sn,
            "simpleCodeType": "wsy",
            "account": "gdyouzheng",
            "branchId": "2",
            "shopId": ""
        }
        response = requests.post(url=url, data=body)
        result = response.json()
        if result['returnCode'] == 'success':
            try:
                shop_id = result['list'][0]['shopId']
                business_no = result['list'][0]['shop_account']
            except:
                shop_id = 'aaaaaa'
                business_no = 'aaaaaa'
            merchant = Merchant.objects.filter(ruiyinxinMerchantID=shop_id).first()
            if merchant:
                query.merchant_id = merchant.id
                query.save()
                MerchantNFCDeviceTrade.objects.filter(sn=query.sn).update(merchant_id=merchant.id, level_id=merchant.level_id)
            else:
                merchant = add_merchant_info(business_no)['merchant']
                if not merchant:
                    print(business_no)
                else:
                    query.merchant_id = merchant.id
                    query.save()
                    MerchantNFCDeviceTrade.objects.filter(sn=query.sn).update(merchant_id=merchant.id, level_id=merchant.level_id)


def statistics_white_merchant():
    '''统计得奖商户'''
    today = datetime.datetime.now() + datetime.timedelta(hours=12)
    check_activity = MerchantEightEightActivity.objects.filter(activity_start_time__lte=today, activity_end_time__gte=today, activity_type=2).first()
    trade_time_begin = (check_activity.activity_start_time - datetime.timedelta(days=7)).strftime("%Y-%m-%d 00:00:00")
    trade_time_end = (check_activity.activity_end_time - datetime.timedelta(days=7)).strftime("%Y-%m-%d 23:59:59")
    print(trade_time_begin, trade_time_end)
    conn = pymysql.connect(host=settings.DATABASES['default']['HOST'],
                           port=settings.DATABASES['default']['PORT'],
                           database=settings.DATABASES['default']['NAME'],
                           user=settings.DATABASES['default']['USER'],
                           password=settings.DATABASES['default']['PASSWORD'])
    cursor = conn.cursor(cursor=pymysql.cursors.SSDictCursor)
    sql = f'''SELECT b.*, c.wyfMerchantID,level_id FROM (SELECT a.* FROM (SELECT merchant_id,COUNT(*) AS count,GROUP_CONCAT(DISTINCT DATE_FORMAT(trade_time,'%Y-%m-%d') ORDER BY trade_time)AS trade_time FROM tb_merchant_nfc_device_trade WHERE pay_type=1 AND trade_time >= "{trade_time_begin}" AND trade_time <= "{trade_time_end}" AND total_amount>=3 AND merchant_id IS NOT NULL GROUP BY merchant_id HAVING COUNT(*)>=30)AS a WHERE CHARACTER_LENGTH(a.trade_time)>=32)AS b LEFT JOIN (SELECT id,wyfMerchantID,level_id FROM tb_merchant)AS c ON b.merchant_id=c.id;'''
    cursor.execute(sql)
    rows = cursor.fetchall()
    cursor.close()
    conn.close()
    for row in rows:
        defaults = {}
        defaults['business_no'] = row['wyfMerchantID']
        defaults['activity_id'] = check_activity.id
        defaults['is_win_type'] = 2
        defaults['level_id'] = row['level_id']
        MerchantEightEightWhiteTable.objects.get_or_create(defaults=defaults, activity_id=check_activity.id, business_no=row['wyfMerchantID'])
    return rows


def get_nfc_trade_paytype():
    '''获取交易方式'''
    today = datetime.datetime.now()
    yesterday = today - datetime.timedelta(days=1)
    trade_time_begin = yesterday.strftime("%Y-%m-%d 00:00:00")
    trade_time_end = yesterday.strftime("%Y-%m-%d 23:59:59")
    trade_set = MerchantNFCDeviceTrade.objects.filter(trade_time__gte=trade_time_begin, trade_time__lte=trade_time_end, merchant_id__isnull=False, pay_type__isnull=True)
    merchant_id_lsit = list(trade_set.values_list('merchant_id', flat=True))
    merchant_set = Merchant.objects.filter(id__in=merchant_id_lsit)
    url = 'https://manage.gdwxyf.com/internal/searchorders.do'
    body = {}
    body['channel'] = 'all'
    body['start'] = trade_time_begin
    body['end'] = trade_time_end
    body['orderStatus'] = 'all'
    body['orderType'] = 'all'
    body['payType'] = 'NFC'
    body['agentId'] = 'all'
    body['branchId'] = '2'
    body['account'] = 'gdyouzheng'
    # trade_data = {}
    trade_data_list = []
    for merchant in merchant_set:
        business_no = merchant.wyfMerchantID
        print(business_no)
        body['shopId'] = business_no
        response = requests.post(url=url, data=body)
        result = response.json()
        if 'showList' in result:
            showList = result['showList']
            for i in showList:
                if 'channelTradeNo' in i and 'payType' in i:
                    # trade_data[i['channelTradeNo']] = i['payType']
                    trade_data_list.append(i['channelTradeNo'])
    MerchantNFCDeviceTrade.objects.filter(trade_time__gte=trade_time_begin, trade_time__lte=trade_time_end, merchant_id__isnull=False, pay_type__isnull=True, transaction_id__in=trade_data_list).update(pay_type=1)
    MerchantNFCDeviceTrade.objects.exclude(transaction_id__in=trade_data_list).filter(trade_time__gte=trade_time_begin, trade_time__lte=trade_time_end, merchant_id__isnull=False, pay_type__isnull=True).update(pay_type=2)
    # for trade in trade_set:
    #     print(trade.transaction_id)
    #     if trade.transaction_id in trade_data:
    #         trade.pay_type = 1
    #     else:
    #         trade.pay_type = 2
    #     trade.save()


def get_nfc_trade_paytype2():
    '''获取交易方式'''
    today = datetime.datetime.now()
    yesterday = today - datetime.timedelta(days=1)
    trade_time_begin = yesterday.strftime("%Y-%m-%d 00:00:00")
    trade_time_end = yesterday.strftime("%Y-%m-%d 23:59:59")
    trade_set = MerchantNFCDeviceTrade.objects.filter(trade_time__gte=trade_time_begin, trade_time__lte=trade_time_end, merchant_id__isnull=False)
    merchant_id_lsit = list(trade_set.values_list('merchant_id', flat=True))
    merchant_set = Merchant.objects.filter(id__in=merchant_id_lsit)
    url = 'https://manage.gdwxyf.com/internal/searchorders.do'
    body = {}
    body['channel'] = 'all'
    body['start'] = trade_time_begin
    body['end'] = trade_time_end
    body['orderStatus'] = 'all'
    body['orderType'] = 'all'
    body['payType'] = 'NFC'
    body['agentId'] = 'all'
    body['branchId'] = '2'
    body['account'] = 'gdyouzheng'
    # trade_data = {}
    trade_data_list = []
    for merchant in merchant_set:
        business_no = merchant.wyfMerchantID
        print(business_no)
        body['shopId'] = business_no
        response = requests.post(url=url, data=body)
        result = response.json()
        if 'showList' in result:
            showList = result['showList']
            for i in showList:
                if 'channelTradeNo' in i:
                    channelTradeNo = i['channelTradeNo']
                    if 'subOpenid'in i:
                        subOpenid = i['subOpenid']
                    else:
                        subOpenid = None
                    if channelTradeNo:
                        MerchantNFCDeviceTrade.objects.filter(transaction_id=channelTradeNo).update(pay_type=1, smid=subOpenid)
                    else:
                        totalNormal = i['totalNormal']
                        pay_time = datetime.datetime.strptime(i['timeEnd'], '%Y-%m-%d %H:%M:%S')
                        pay_time_start = pay_time - datetime.timedelta(seconds=3)
                        pay_time_end = pay_time + datetime.timedelta(seconds=3)
                        MerchantNFCDeviceTrade.objects.filter(trade_amount=totalNormal, trade_time__gte=pay_time_start, trade_time__lte=pay_time_end, merchant_id=merchant.id).update(pay_type=1, smid=subOpenid)
                    # trade_data[i['channelTradeNo']] = i['payType']
                    trade_data_list.append(i['channelTradeNo'])
    MerchantNFCDeviceTrade.objects.filter(trade_time__gte=trade_time_begin, trade_time__lte=trade_time_end, merchant_id__isnull=False, pay_type__isnull=True).update(pay_type=2)
    # for trade in trade_set:
    #     print(trade.transaction_id)
    #     if trade.transaction_id in trade_data:
    #         trade.pay_type = 1
    #     else:
    #         trade.pay_type = 2
    #     trade.save()


def refresh_authorization():
    channel = Channel.objects.get(id=14)
    refreshToken = channel.token
    url = f'https://newmanage.gdwxyf.com/admin-api/admin-api/system/auth/refresh-token?refreshToken={refreshToken}'
    response = requests.post(url=url)
    result = response.json()
    if result['code'] != 0:
        refreshToken = update_refreshToken()
        channel.token = refreshToken
        channel.save()
        url = f'https://newmanage.gdwxyf.com/admin-api/admin-api/system/auth/refresh-token?refreshToken={refreshToken}'
        response = requests.post(url=url)
        result = response.json()
    return result


def get_token_text_secretKey():
    headers = {"Content-Type": "application/json"}
    a = 1
    while True:
        if a >= 60:
            break
        time.sleep(1)
        captcha_url = 'https://newmanage.gdwxyf.com/admin-api/admin-api/system/captcha/get'
        captcha_body = {
            "platform": "1",
            "captchaType": "blockPuzzle",
            "clientUid": f"slider-{uuid.uuid4()}",
            "ts": int(time.time()*1000)
        }
        captcha_response = requests.post(url=captcha_url, data=json.dumps(captcha_body), headers=headers)
        captcha_result = captcha_response.json()['repData']
        token = captcha_result['token']
        secretKey = captcha_result['secretKey']
        bg_ele = captcha_result['originalImageBase64']
        sli_ele = captcha_result['jigsawImageBase64']
        sv = SlideVerificationCode()
        try:
            distance = sv.get_element_slide_distance(sli_ele, bg_ele)
            # distance = sv.get_element_slide_distance1(bg_ele)
            distance = 108
        except:
            continue
        text = '{"x":' + f'{distance}' +',"y":5}'
        pointJson = encrypt_ECB(text, secretKey)
        body = {
            "platform": "1",
            "captchaType": "blockPuzzle",
            "pointJson": pointJson,
            "token": token
        }
        url = 'https://newmanage.gdwxyf.com/admin-api/admin-api/system/captcha/check'
        response = requests.post(url=url, data=json.dumps(body), headers=headers)
        result = response.json()
        if result['repCode'] == '0000':
            return secretKey, text, token
        a += 1
    return '', '', ''


def update_refreshToken():
    headers = {"Content-Type": "application/json"}
    secretKey, text, token = get_token_text_secretKey()
    login_url = 'https://newmanage.gdwxyf.com/admin-api/admin-api/cmpay-login/login'
    captchaVerification = encrypt_ECB(f'{token}---{text}', secretKey)
    login_body = {
        "platform": "1",
        "username": "gdyouzheng",
        "password": "youzhenggd",
        "captchaVerification": captchaVerification
    }
    login_response = requests.post(url=login_url, data=json.dumps(login_body), headers=headers)
    result = login_response.json()
    refreshToken = result['data']['refreshToken']
    return refreshToken


def get_nfc_trade_paytype1():
    today = datetime.datetime.now()
    yesterday = today - datetime.timedelta(days=1)
    trade_time_begin = yesterday.strftime("%Y-%m-%d 00:00:00")
    trade_time_end = yesterday.strftime("%Y-%m-%d 23:59:59")
    trade_set = MerchantNFCDeviceTrade.objects.filter(trade_time__gte=trade_time_begin, trade_time__lte=trade_time_end, smid__isnull=True)
    # trade_set = MerchantNFCDeviceTrade.objects.filter(smid__isnull=True, id__gte=507031)
    url = 'https://newmanage.gdwxyf.com/admin-api/admin-api/ordersNew/searchAgentOrders'
    body = {
        "branchId": 2,
        "platform": "1",
        "shopId": "",
        "start": "2024-10-12 00:00:00",
        "end": "2024-10-24 23:59:59",
        "channelTradeNo": "2024102223001451231435007336",
        "pageNo": 1,
        "pageSize": 10
    }
    accessToken = 'a5cef02e624a436cbaf09e44157b8f40'
    headers = {"authorization": f"Bearer {accessToken}", 'Content-Type': 'application/json'}
    for trade in trade_set:
        print(trade.id)
        transaction_id = trade.transaction_id
        trade_time = trade.trade_time
        start = trade_time.strftime("%Y-%m-%d 00:00:00")
        end = trade_time.strftime("%Y-%m-%d 23:59:59")
        body['start'] = start
        body['end'] = end
        body['channelTradeNo'] = transaction_id
        response = requests.post(url=url, data=json.dumps(body), headers=headers)
        result = response.json()
        if result['code'] == 401:
            authorization_data = refresh_authorization()
            if authorization_data['code'] != 0:
                print('刷新令牌失效')
                return '刷新令牌失效'
            accessToken = authorization_data['data']['accessToken']
            refreshToken = authorization_data['data']['refreshToken']
            channel = Channel.objects.get(id=14)
            channel.token = refreshToken
            channel.save()
            headers['Authorization'] = f"Bearer {accessToken}"
            response = requests.post(url=url, data=json.dumps(body), headers=headers)
            result = response.json()
        result = result['data']['list']
        if result:
            shopId = result[0]['shopId']
            payType = result[0]['payType']
            subOpenid = result[0]['subOpenid']
            merchant = Merchant.objects.filter(ruiyinxinMerchantID=shopId).first()
            if merchant:
                trade.merchant_id = merchant.id
                trade.level_id = merchant.level_id
            if payType == 'NFC':
                trade.pay_type = 1
            else:
                trade.pay_type = 2
            trade.smid = subOpenid
            trade.shop_id = shopId
            trade.save()


def get_nfc_sn():
    '''获取nfc设备'''
    sn_lists = list(MerchantNFCDevice.objects.all().values_list('sn', flat=True))
    print(sn_lists)


def searchmerchantmsg(business_no):
    '''查询商户进件情况'''
    md5 = hashlib.md5()  # 使用MD5加密模式
    md5.update(str(business_no).encode('utf-8'))  # 将参数字符串传入
    shop_id = md5.hexdigest()  # 完成加密并转为大写
    url = 'https://api.gdwxyf.com/api/searchmerchantmsg.do'
    key = '689E09580658748F8839519B41FE27B2'
    program_id = '202410169264091834'
    body = {}
    body['program_id'] = program_id
    body['shop_id'] = shop_id
    sign = get_sign(body, key)
    body['sign'] = sign
    # print(body)
    response = requests.post(url=url, json=body)
    return response.json()


if __name__ == '__main__':
    pass
    # merchant_list = []
    # for merchant in merchant_list:
    #     synchronization_settlementrecord_aaaaa(merchant)

    # synchronous_settlerecord3()
    # print(create_contract_table('广州上邑网络科技有限公司', '836581773990578', '44512219810329001X', '9144010130465680X6'))
    # print(query_merinid('92441803MA53ACP99J'))
    # print(get_nfc_trade())
    print(searchmerchantmsg('6022869178'))